###########################################################
# Manages user creation and authentication.
###########################################################
package EP::EPC::Core::User_Management;

use strict;

use EP::Common;
use EP::Common::Error qw ( :try );

use EP::Common::DBI::User;

use EP::Common::General;
use EP::Common::Data;

use Crypt::PasswdMD5;

our @ISA = qw ( EP::EPC::Core::Component );

sub
process_component
    {
    my $self = shift;
    my %user_props;

    foreach ( qw ( username password first_name last_name institute department address telephone email ) )
        {
        $user_props{$_} = $self->{query}->param($_);
        }

    my $user;

    if ( $self->{query}->param("status") eq "create_user" )
        {
        # TO DO: forcing NOT to use SVG and so-called "advanced level"
        $user_props{"visualization_format"} = 1;
        $user_props{"user_level"} = 1;

        # creating new user
        $user = EP::Common::DBI::User->create( \%user_props );
        die "There was an error registering user." if not $user;
        }
    else
        {
        $user = EP::Common::DBI::User->authenticate(\%user_props);
        throw EP::Common::Error( -value => UM_INVALID_USERNAME_PASSWORD ) if not $user;

        $user->last_login( localtime() . "" );
        }

    $self->{session}->owner($user);
    $self->{session}->keep_alive();

    my ($user_homefolder) = EP::Common::DBI::Folder->search( name => $user->username );

    if ( $user->username eq "guest" )
        {
        $self->{session}->current_root_dataset(undef);
        $self->{session}->current_action(undef);
        $self->{session}->current_folder($user_homefolder);
        }
    else
        {
        $self->{session}->current_folder( $user->last_folder )              if $user->last_folder;
        $self->{session}->current_root_dataset( $user->last_root_dataset )  if $user->last_root_dataset;
        $self->{session}->current_action( $user->last_action )              if $user->last_action;

        $self->{session}->current_folder($user_homefolder)                  if not $self->{session}->current_folder;
        if ( not $self->{session}->current_root_dataset )
            {
            my ($first_dataset) = EP::Common::DBI::Dataset->search_where( { owner => $user, folder => $user_homefolder->id }, { order_by => 'created' } );
            $self->{session}->current_root_dataset($first_dataset);
            }
        }

    my $process_result = { username => $user->username };

    $self->{CD}->{process_result} = $process_result;
    return OK;
    }

1;
